<template>
  <div class="article-container">
    <div class="article box-shadow">
      <h1>{{ ArticleData.articleTitle }}</h1>
      <div class="user-panel box">
        <div class="user-top">
          <div class="user-name">{{ ArticleData.author }}</div>
          <span>  {{ dayjs(ArticleData.updateDate).format('YYYY-MM-DD') }} </span>
          <div class="flex-row" @click="likesClick()">
            <svg-icon icon-class="likes" v-if="ArticleData.isLike === 0" />
            <svg-icon icon-class="likesed" v-else />
            <div>{{ ArticleData.likes }}</div>
          </div>
          <div class="edit"><span @click="goEdit(ArticleData.articleId, ArticleData.author)" style="color: #8fb0c9;">编辑</span></div>
        </div>
        <div class="user-bottn">
          <span>文章标签:<el-tag v-for="item in ArticleData.articleTags" style="margin-right: 10px">{{ item }}</el-tag></span>
        </div>
      </div>
      <el-divider />
      <div class="article-content">
        <div class="body">
          <div v-html="ArticleData.articleContent"></div>
        </div>
      </div>
    </div>

    <div class="article-common-box article box-shadow">
      <div class="title" style="margin-bottom:14px">评论数{{ ArticleData.commentCount }}</div>
      <div class="content">
        <div class="avatar">
          <img class="avatar-img"
            :src="userInfo ? userInfo.avatar : defaultAvatar" />
        </div>
        <div class="input-box">
          <el-input v-model="form.commentContent" maxlength="200" show-word-limit :autosize="{ minRows: 3 }"
            type="textarea" placeholder="请发表你的意见" />
          <div class="box-center">
            <el-button type="primary" plain @click="addComment()">发送</el-button>
          </div>
        </div>
      </div>
      <div class="common-list-box">
        <div class="item" v-for="item in pageData.commentList.list">
          <div class="avatar">
            <img class="avatar-img"
              :src="item.avatar ? item.avatar : defaultAvatar" />
          </div>
          <div class="common-content">
            <div>{{ item.username }}</div>
            <div class="content">{{ item.commentContent }}</div>
            <div class="common-bar">
              <span>{{ TimeDiff(item.updateTime) }}</span>
              <span @click="showInput(item)">回复</span>
            </div>
            <use-input :model-value="replyForm" @update="updateComment" v-show="item.isShowInput" />
            <!--回复列表-->
            <div class="reply-common-box" v-if="item.replyCount > 0">
              <span @click="getCommentReplyList(item.id)" v-if="item.isShow">查看全部{{ item.replyCount }}条回复</span>
            </div>
            <template v-if="item.replyCommentList">
              <div class="reply-common-list" v-for="replyItem in item.replyCommentList">
                <div class="item">
                  <div class="avatar">
                    <img class="avatar-img"
                      :src="replyItem.avatar ? replyItem.avatar : defaultAvatar" />
                  </div>
                  <div class="common-content">
                    <div>{{ replyItem.username }}<span v-if="replyItem.toUserName"><span class="reply-text">回复</span>{{
                      replyItem.toUserName }}</span></div>
                    <div class="content">{{ replyItem.replyContent }}</div>
                    <div class="common-bar">
                      <span>{{ TimeDiff(replyItem.updateTime) }}</span>
                      <span @click="showInput(replyItem)">回复</span>
                    </div>
                    <use-input :model-value="replyForm" @update="updateComment" v-show="replyItem.isShowInput" />
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArticleDetail, addBookComment, likeArticle } from '@/api/article'
import { commentList, commentReplyList } from '@/api/home'
import { storeToRefs } from 'pinia'
import { useUser } from '../stores/user'
import dayjs from 'dayjs'
import UseInput from '@/components/UseInput.vue'
import SvgIcon from '@/components/SvgIcon.vue'
import { TimeDiff } from '@/utils/dateUtil.js'
import { ElMessage } from 'element-plus'


const defaultAvatar = 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'

const route = useRoute()
const router = useRouter()
const { userInfo } = storeToRefs(useUser())


// 文章详情
const ArticleData = ref({})
async function getDetail() {
  ArticleData.value = await ArticleDetail(route.query.articleId + '')
  ArticleData.value.articleTags = ArticleData.value.articleTags.split(",");
}
getDetail()


// 点赞
async function likesClick() {

  event.stopPropagation();
  const res = await likeArticle(route.query.articleId + '')
  if (res) {
    ElMessage.success(res)
  }
  if (ArticleData.value.isLike === 0) {
    ArticleData.value.isLike = 1
    ArticleData.value.likes++
  }

}



// 获取文章评论列表
const pageData = reactive({
  commentList: {},
  size: 10,
  page: 1
})
async function getCommentPage() {
  pageData.commentList = await commentList({ articleId: route.query.articleId + '', curr: pageData.page, limit: pageData.size })
  if (pageData.commentList.list) {
    pageData.commentList.list.forEach(item => {
      item.isShow = true
      item.isShowInput = false
    })

  }
}
getCommentPage()





// 评论文章
const form = reactive({
  articleId: route.query.articleId + '',
  userId: null,
  commentContent: ''
})
async function addComment() {
  try {
    if (form.commentContent.length > 0) {
      const res = await addBookComment(form)
      ArticleData.value.commentCount++
      await getCommentPage()
      ElMessage.success(res)
    } else {
      ElMessage.error("评论内容为空")
    }
  }  finally {
    form.commentContent = ''
  }
}


async function getCommentReplyList(id) {
  try {
    const res = await commentReplyList(id)
    res.forEach(item => {
      item.isShowInput = false
    })
    if (pageData.commentList.list) {
      pageData.commentList.list.forEach(item => {
        if (item.id == id) {
          item.replyCommentList = res
          item.isShow = false
        }
      })
    }
  } catch (error) {
    ElMessage.error(error)
  }
}



const replyForm = reactive({
  commentId: '',
  replyContent: '',
  replyId: ''
})

function showInput(item) {
  replyForm.replyId = ''
  if (item.isShowInput === false) {
    // 防止多个输入框同时出现共享
    pageData.commentList.list.forEach(item => {
      item.isShowInput = false
      if (item.replyCommentList) {
        item.replyCommentList.forEach(i => {
          i.isShowInput = false
        });
      }
    })
    item.isShowInput = true
    if (item.commentId) {
      replyForm.commentId = item.commentId
      replyForm.replyId = item.userId
    } else {
      replyForm.commentId = item.id
    }
  } else {
    item.isShowInput = false
  }
}


// 子评论列表数据更新
function updateComment(id) {

  // getCommentPage()
  getCommentReplyList(id)

}



function goEdit(id, author) {
  if(userInfo.value.username === author) {
    router.push(`/publish?articleId=${id}`)
  } else {
    ElMessage.error('您没有权限修改该文章！')
  }
}

</script>

<style lang="scss" scoped>
.article-container {
  position: relative;
  max-width: 1140px;
  margin: 0 auto;
}

.article {
  position: relative;
  padding: 2.667rem;
  z-index: 1;
  overflow: hidden;
  background-color: #fff;
  box-sizing: border-box;
  border-radius: 4px 4px 0 0;
}

.user-top {
  display: flex;

  .user-name {
    margin-right: 20px;
    max-width: 232px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  span {
    margin-right: 16px;
    color: #8a919f;
  }

  .edit {

    /* align-self: end; */
    flex: 1;
    text-align: end;
  }



}

.user-bottn {
  margin-top: 16px;
}

.box {
  position: relative;
  background: #f8f8f8;
  border-radius: 4px;
  padding: 16px;
}

.article-content {
  padding: 16px;
}

.article-common-box {
  margin-top: 16px;
  padding: 1.667rem 2.667rem 2.667rem 2.667rem;

  .title {
    font-size: 18px;
    font-weight: 600;
    line-height: 30px;
  }
}

.content {
  display: flex;
  align-items: flex-start;
}

.avatar {
  margin-right: 16px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.avatar-img {
  width: 100%;
  height: 100%;
  background-size: cover;
  border-radius: 50%;
}

.input-box {
  flex: 1;

}

.item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.reply-common-list {
  margin-top: 20px;
}

.common-content {
  .content {
    margin: 12px 0;
  }

  .common-bar {
    span {
      margin-right: 16px;
      color: #8a919f;
    }
  }
}

.reply-common-box {
  margin: 12px 0;
  color: #8a919f;

  .reply-text {
    font-weight: bold;
    margin: auto 10px;
  }
}
</style>